<template>
  <el-button type="primary" :icon="CirclePlus" class="add-btn" @click="addType"> 新增字典类型 </el-button>
  <el-input v-model="filterText" class="filter-input" placeholder="输入字典项筛选" />
  <el-tree
    ref="treeRef"
    style="max-width: 250px"
    class="filter-tree"
    :data="dictData"
    :props="defaultProps"
    default-expand-all
    :expand-on-click-node="false"
    :filter-node-method="filterNode"
    @node-click="handleNodeClick"
  >
    <template #default="{ node, data }">
      <div class="custom-tree-node">
        <span>{{ node.label }}</span>
        <div>
          <template v-if="data.dictId === 0">
            <el-button type="primary" link :icon="Refresh" @click="e => refreshType(e)"> </el-button>
          </template>
          <template v-else>
            <el-button type="primary" link :icon="EditPen" @click="e => editType(e, data)"> </el-button>
            <el-button type="primary" style="margin-left: 4px" link :icon="Delete" @click="e => delType(e, data)"></el-button>
          </template>
        </div>
      </div>
    </template>
  </el-tree>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from "vue";
import { ElMessage, ElMessageBox, type FilterNodeMethodFunction, type TreeInstance } from "element-plus";
import { Delete, EditPen, CirclePlus, Refresh } from "@element-plus/icons-vue";
import { getDictTypeAllApi, delDictTypeApi } from "@/api/modules/dict";
import mittBus from "@/utils/mittBus";

interface Tree {
  [key: string]: any;
}

const filterText = ref("");
const treeRef = ref<TreeInstance>();

const defaultProps = {
  children: "children",
  label: "dictName"
};

watch(filterText, val => {
  treeRef.value!.filter(val);
});

const filterNode: FilterNodeMethodFunction = (value: string, data: Tree) => {
  if (!value) return true;
  return data.dictName.includes(value);
};

const dictData = ref<Tree[]>([
  {
    dictId: 0,
    dictName: "全部字典",
    children: []
  }
]);

onMounted(() => {
  getDictTypeAll();
});

const getDictTypeAll = async () => {
  const res = await getDictTypeAllApi();
  if (res.code === 200) {
    const types = res.data.map(item => {
      return {
        dictId: item.dictId,
        dictName: item.dictName,
        dictType: item.dictType,
        status: item.status
      };
    });
    dictData.value = [
      {
        dictId: 0,
        dictName: "全部字典",
        children: types
      }
    ];
  }
};

defineExpose({
  getDictTypeAll
});

const refreshType = (event: any) => {
  event.stopPropagation();
  getDictTypeAll();
};

const emit = defineEmits(["addType", "editType"]);
// 新增字典类型
const addType = () => {
  emit("addType");
};

// 编辑字典类型
const editType = (event: any, data: any) => {
  event.stopPropagation();
  emit("editType", data);
};

// 删除字典类型
const delType = async (event: any, data: any) => {
  event.stopPropagation();
  const dictIds = [data.dictId];
  const delMsg = `是否确认删除字典编号为"${dictIds.join(",")}"的数据项?`;
  delMsgBox(delMsg, dictIds, dictIds => delDictType(dictIds));
};

const delDictType = async (dictIds: number[]) => {
  const res = await delDictTypeApi({ dictIds });
  if (res.code === 200) {
    ElMessage.success("删除成功");
    getDictTypeAll();
  } else {
    ElMessage.error(res.msg);
  }
};

const delMsgBox = (delTitle: string, delIds: number[], confirm: (delIds: number[]) => void) => {
  ElMessageBox.confirm(delTitle, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      confirm(delIds);
    })
    .catch(() => {
      console.log("取消");
    });
};

const handleNodeClick = (data: { [key: string]: any }) => {
  mittBus.emit("dictTypeChange", data);
};
</script>

<style lang="scss" scoped>
.add-btn,
.filter-input {
  width: 100%;
  max-width: 250px;
  margin-bottom: 10px;
}
.custom-tree-node {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
  font-size: 14px;
}
</style>
